import axios from 'axios'
import { API_CONFIG, ERROR_MESSAGES } from '@/config/api'

// 创建axios实例
const api = axios.create({
  baseURL: API_CONFIG.BASE_URL,
  timeout: API_CONFIG.TIMEOUT,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证token
    const token = localStorage.getItem('authToken')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response) {
      // 服务器返回错误状态码
      console.error('API Error:', error.response.data)
      // 处理不同的错误格式：message 或 error 字段
      const errorMessage = error.response.data.message || error.response.data.error || '请求失败'
      return Promise.reject(new Error(errorMessage))
    } else if (error.request) {
      // 请求发送失败
      console.error('Network Error:', error.request)
      return Promise.reject(new Error('网络连接失败'))
    } else {
      // 其他错误
      console.error('Error:', error.message)
      return Promise.reject(error)
    }
  }
)

export class GameService {
  // 游戏相关API - 对接后端实际接口
  static async createGame(gameData) {
    try {
      // 生成房间代码
      const code = this.generateRoomCode()
      
      const response = await api.post(API_CONFIG.ENDPOINTS.CREATE_GAME, {
        name: gameData.name,
        code: code,
        creatorNickName: gameData.creatorNickName,
        maxPlayers: gameData.maxPlayers || API_CONFIG.GAME.MAX_PLAYERS,
        gameDuration: gameData.gameDuration || API_CONFIG.GAME.DEFAULT_DURATION,
        password: gameData.password || null
      })
      return response.data
    } catch (error) {
      throw new Error(this.handleError(error, ERROR_MESSAGES.GAME_CREATION_FAILED))
    }
  }

  static async joinGame(gameCode, playerNickName, password = null) {
    try {
      // 如果密码为null或undefined，转换为空字符串
      const passwordToSend = password || ''
      
      console.log('加入游戏API调用:', {
        endpoint: API_CONFIG.ENDPOINTS.JOIN_GAME,
        data: { gameCode, playerNickName, password: passwordToSend }
      })
      const response = await api.post(API_CONFIG.ENDPOINTS.JOIN_GAME, {
        gameCode,
        playerNickName,
        password: passwordToSend
      })
      console.log('加入游戏API响应:', response.data)
      return response.data
    } catch (error) {
      console.error('加入游戏API错误:', error)
      throw new Error(this.handleError(error, ERROR_MESSAGES.GAME_JOIN_FAILED))
    }
  }

  static async leaveGame(gameCode, playerNickName) {
    try {
      console.log('离开游戏API调用:', {
        endpoint: API_CONFIG.ENDPOINTS.LEAVE_GAME,
        data: { gameCode, playerNickName }
      })
      const response = await api.post(API_CONFIG.ENDPOINTS.LEAVE_GAME, {
        gameCode,
        playerNickName
      })
      console.log('离开游戏API响应:', response.data)
      return response.data
    } catch (error) {
      console.error('离开游戏API错误:', error)
      throw new Error(this.handleError(error, '离开游戏失败'))
    }
  }

  static async getGame(gameId) {
    try {
      const response = await api.get(API_CONFIG.ENDPOINTS.GET_GAME(gameId))
      return response.data
    } catch (error) {
      throw new Error(this.handleError(error, ERROR_MESSAGES.GAME_NOT_FOUND))
    }
  }

  static async getGameByCode(code) {
    try {
      const response = await api.get(API_CONFIG.ENDPOINTS.GET_GAME_BY_CODE(code))
      return response.data
    } catch (error) {
      throw new Error(this.handleError(error, ERROR_MESSAGES.GAME_NOT_FOUND))
    }
  }

  static async getGameList() {
    try {
      console.log('调用获取游戏列表API:', API_CONFIG.ENDPOINTS.GET_GAME_LIST)
      const response = await api.get(API_CONFIG.ENDPOINTS.GET_GAME_LIST)
      console.log('获取游戏列表API响应:', response)
      console.log('响应数据:', response.data)
      return response.data
    } catch (error) {
      console.error('获取游戏列表失败:', error)
      console.error('错误详情:', error.response?.data)
      throw new Error(error.response?.data?.error || '获取游戏列表失败')
    }
  }

  static async deleteGame(gameId) {
    try {
      console.log('删除游戏API调用:', API_CONFIG.ENDPOINTS.DELETE_GAME(gameId))
      const response = await api.delete(API_CONFIG.ENDPOINTS.DELETE_GAME(gameId))
      console.log('删除游戏API响应:', response.data)
      return response.data
    } catch (error) {
      console.error('删除游戏API错误:', error)
      throw new Error(this.handleError(error, ERROR_MESSAGES.DELETE_GAME_FAILED))
    }
  }

  static async submitPaintAction(gameId, playerId, x, y, brushSize) {
    try {
      const response = await api.post(API_CONFIG.ENDPOINTS.PAINT_ACTION, {
        gameId,
        playerId,
        x,
        y,
        brushSize
      })
      return response.data
    } catch (error) {
      throw new Error(this.handleError(error, ERROR_MESSAGES.PAINT_ACTION_FAILED))
    }
  }

  // 工具方法
  static handleError(error, defaultMessage) {
    console.log('处理错误:', error)
    if (error.response) {
      // 服务器返回错误
      console.log('服务器错误响应:', error.response.data)
      return error.response.data?.message || error.response.data?.error || defaultMessage
    } else if (error.request) {
      // 网络错误
      console.log('网络错误:', error.request)
      return ERROR_MESSAGES.NETWORK_ERROR
    } else {
      // 其他错误
      console.log('其他错误:', error.message)
      return error.message || ERROR_MESSAGES.UNKNOWN_ERROR
    }
  }

  // 工具方法
  static generateRoomCode() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    let result = ''
    for (let i = 0; i < 6; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return result
  }

  static validateRoomCode(roomCode) {
    return /^[A-Z0-9]{6}$/.test(roomCode)
  }

  static validatePlayerName(playerName) {
    return playerName.trim().length >= 2 && playerName.trim().length <= 15
  }

  static validateRoomName(roomName) {
    return roomName.trim().length >= 3 && roomName.trim().length <= 20
  }
}

// 模拟API服务（用于开发阶段）
export class MockGameService {
  static async getRooms() {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    return {
      success: true,
      data: [
        {
          id: '1',
          name: '欢乐涂色房',
          status: 'waiting',
          currentPlayers: 2,
          maxPlayers: 4,
          gameDuration: 180,
          roomCode: 'ABC123',
          createdAt: new Date().toISOString()
        },
        {
          id: '2',
          name: '竞技涂色场',
          status: 'playing',
          currentPlayers: 3,
          maxPlayers: 6,
          gameDuration: 240,
          roomCode: 'DEF456',
          createdAt: new Date().toISOString()
        },
        {
          id: '3',
          name: '休闲涂色屋',
          status: 'waiting',
          currentPlayers: 1,
          maxPlayers: 3,
          gameDuration: 300,
          roomCode: 'GHI789',
          createdAt: new Date().toISOString()
        }
      ]
    }
  }

  static async createRoom(roomData) {
    await new Promise(resolve => setTimeout(resolve, 800))
    
    const roomCode = GameService.generateRoomCode()
    const room = {
      id: Date.now().toString(),
      name: roomData.roomName,
      roomCode: roomCode,
      maxPlayers: roomData.maxPlayers,
      gameDuration: roomData.gameDuration,
      currentPlayers: 1,
      status: 'waiting',
      createdAt: new Date().toISOString(),
      owner: {
        id: Date.now().toString(),
        name: roomData.playerName,
        isOwner: true,
        isReady: true,
        color: '#FF6B6B'
      }
    }
    
    return {
      success: true,
      data: room
    }
  }

  static async joinRoom(roomCode, playerData) {
    await new Promise(resolve => setTimeout(resolve, 600))
    
    // 模拟查找房间
    const mockRooms = [
      { id: '1', roomCode: 'ABC123', name: '欢乐涂色房', maxPlayers: 4, currentPlayers: 2 },
      { id: '2', roomCode: 'DEF456', name: '竞技涂色场', maxPlayers: 6, currentPlayers: 3 }
    ]
    
    const room = mockRooms.find(r => r.roomCode === roomCode)
    if (!room) {
      throw new Error('房间码无效')
    }
    
    if (room.currentPlayers >= room.maxPlayers) {
      throw new Error('房间已满员')
    }
    
    const player = {
      id: Date.now().toString(),
      name: playerData.playerName,
      isOwner: false,
      isReady: false,
      color: '#4ECDC4'
    }
    
    return {
      success: true,
      data: {
        room: { ...room, currentPlayers: room.currentPlayers + 1 },
        player: player
      }
    }
  }

  static async startGame() {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    return {
      success: true,
      data: {
        message: '游戏开始',
        gameStatus: 'playing',
        startTime: new Date().toISOString()
      }
    }
  }

  static async submitPaintAction() {
    // 模拟实时处理
    await new Promise(resolve => setTimeout(resolve, 100))
    
    return {
      success: true,
      data: {
        message: '涂色动作已处理',
        actionId: Date.now().toString()
      }
    }
  }
}

// 始终使用真实API服务
export const gameService = GameService